package com.skydoves.chatgpt.feature.chat.ddd.messages

import android.app.Application
import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.skydoves.chatgpt.core.navigation.AppComposeNavigator
import com.example.core_database.entities.ChatMessage
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.delay
import kotlin.random.Random

@Composable
fun BotMessagesScreen(
  botId: String,
  botName : String ,
  conversationId:String,
  composeNavigator: AppComposeNavigator,
  sendToCozeViewModel: SendToCozeViewModel= hiltViewModel(),
  onBackPressed: () -> Unit = { composeNavigator.navigateUp() },
){
  var uid : String
  sendToCozeViewModel.getRealUid {s->
    uid=s
    Log.i("uiduid",uid)
  }

  val application = LocalContext.current.applicationContext as Application
  val viewModel: ChatMessagesViewModel = viewModel(
    factory = ChatMessagesViewModelFactory(application, botId)
  )

  val backAction = {
    onBackPressed()
  }
  BackHandler(enabled = true, onBack = backAction)

  // 获取 botId 对应的消息列表
  val rawMessages by viewModel.getMessages(botId).collectAsState()


  val listState = rememberLazyListState()
  LaunchedEffect(rawMessages) {
    listState.scrollToItem(rawMessages.size)
  }

  Box(
    modifier = Modifier
      .fillMaxSize()
  ){
    Scaffold(
      modifier = Modifier.fillMaxSize(),
      topBar = {
        CenterAlignedTopAppBar(
          title = {
            Text(botName, maxLines = 1, overflow = TextOverflow. Ellipsis)
          },
          navigationIcon = {
            IconButton(onClick = backAction) {
              Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
            }
          }
        )
      },

      bottomBar = {
        MessageBottom(
          botId=botId,
          botName=botName,
          conversationId=conversationId,
          viewModel=viewModel
        )
      },

      ){padding->
        LazyColumn(
          state = listState,
          modifier = Modifier
            .background(Color(0xFFE9E9E9))
            .padding(padding)
            .fillMaxSize()
        ) {
          items(rawMessages) { message ->
            MessageItem(message)
          }
        }


    }
  }



}


@Composable
fun MessageItem(message: ChatMessage) {
  Row(
    modifier = Modifier
      .padding(8.dp)
      .fillMaxWidth()
      .padding(
        start = if(message.isSentByUser) 40.dp else 0.dp,
        end = if(message.isSentByUser) 0.dp else 40.dp
      ),
    horizontalArrangement = if (message.isSentByUser) Arrangement.End else Arrangement.Start
  ) {
    Box(
      modifier = Modifier
        .background(
          color = if(message.isSentByUser) Color.Green.copy(alpha = 0.2f) else Color.Gray.copy(alpha = 0.1f),
          shape = RoundedCornerShape(20.dp,20.dp,20.dp,20.dp),
        )
        .padding(start = 20.dp, top = 10.dp, end = 20.dp, bottom = 10.dp)
    ) {
      Text(
        text = message.messageContent,
        color = Color.Black
      )
    }
  }
}


@Composable
fun MessageBottom(
  botId:String,
  botName: String,
  conversationId:String,
  viewModel: ChatMessagesViewModel,
  sendToCozeViewModel: SendToCozeViewModel= hiltViewModel()
){
  var uid="null"
  sendToCozeViewModel.getRealUid {s->
    uid=s
  }

  var messageContent by remember { mutableStateOf("") }
  var resetTimerTrigger by remember { mutableStateOf(false) }// 用于重置定时器

  LaunchedEffect(resetTimerTrigger) {
    delay(15000)
    val randomInt = Random.nextInt(1, 6)
    if(randomInt == 1){
      sendToCozeViewModel.secretChat(uid,botId,conversationId){response->
        val botMessage = ChatMessage(
          userId = uid,
          botId = botId,
          messageContent = response.data,
          timestamp = System.currentTimeMillis(),
          isSentByUser = false
        )
        viewModel.addMessage(botId, botMessage,botName)
        resetTimerTrigger = !resetTimerTrigger
      }
    }else{
      resetTimerTrigger = !resetTimerTrigger
    }

  }

  Box(
    modifier = Modifier
      .fillMaxWidth()  // 让整个屏幕宽度填充
      .padding(bottom = 20.dp, top = 10.dp), // 添加一些边距
    contentAlignment = Alignment.BottomCenter
  ) {
    BasicTextField(
      value = messageContent,
      onValueChange = {
        messageContent = it
        resetTimerTrigger = !resetTimerTrigger
      },
      modifier = Modifier
        .background(Color.White, CircleShape)
        .height(40.dp)
        .fillMaxWidth(0.92f),
      decorationBox = { innerTextField ->
        Row(
          verticalAlignment = Alignment.CenterVertically,
          modifier = Modifier.padding(horizontal = 10.dp)
        ) {
          Box(
            modifier = Modifier.weight(1f),
            contentAlignment = Alignment.CenterStart
          ) {
            innerTextField()
          }
          IconButton(
            onClick = {
              val newMessage = ChatMessage(
                userId = uid,
                botId = botId ,
                messageContent = messageContent,
                timestamp = System.currentTimeMillis(),
                isSentByUser = true
              )
              viewModel.addMessage(botId, newMessage,"User")


              sendToCozeViewModel.sendMessageToCoze(newMessage,conversationId){response->
                val botMessage = ChatMessage(
                  userId = uid,
                  botId = botId,
                  messageContent = response.data,
                  timestamp = System.currentTimeMillis(),
                  isSentByUser = false
                )
                viewModel.addMessage(botId, botMessage,botName)
              }

              messageContent = " "
              resetTimerTrigger = !resetTimerTrigger
            },
          ) {
            Icon(Icons.AutoMirrored.Filled.Send, null)
          }
        }
      }
    )
  }


}






